/**
 * Copyright (c) 2013 onionframework.org
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 */
package org.onionframework.core.config;

import java.io.File;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.configuration.XMLConfiguration;
import org.apache.commons.configuration.reloading.FileChangedReloadingStrategy;
import org.springframework.stereotype.Component;

@Component
public class SystemConfig {

	public static Configuration Config;
	private static String basePath;
	public static String DIALECT_HIBERNATE;
	public static String DIALECT_IBATIS;
	
	static{
		try {
			basePath = new File(SystemConfig.class.getResource("/").toURI().getPath()).getPath();
			initConfig();
		} catch (URISyntaxException e) {
			throw new RuntimeException(e);
		}
	}
	
	/**
	 * 初始化配置,默认读取WEB-INF/classes/config目录及其子目录下的所有配置文件。
	*/
	public static void initConfig() {
		List<Configuration> configs = new ArrayList<Configuration>();
		
		initFileConfig(configs);
		
		Config = new FixedCompositeConfiguration(configs);
	}

	private static void initFileConfig(List<Configuration> configs) {
		try {
			File file = new File(basePath + "/config/");
			if(!file.exists())
				return;
			
			for(File child : file.listFiles()){
				initFileConfig(child,configs);
			}
		} catch (Exception e) {
			throw new RuntimeException("系统配置载入出错！", e);
		}
	}

	private static void initFileConfig(File file, List<Configuration> configs) throws ConfigurationException {
		if(file.isFile()){
			FileChangedReloadingStrategy strategy = new FileChangedReloadingStrategy();
			strategy.setRefreshDelay(60 * 1000);
			
			if(file.getName().endsWith(".xml")){
				XMLConfiguration config = new XMLConfiguration(file);
				config.setReloadingStrategy(strategy);
				configs.add(config);
			}
			else{
				PropertiesConfiguration config = new PropertiesConfiguration(file);
				config.setReloadingStrategy(strategy);
				configs.add(config);
			}
		}else{
			for(File child : file.listFiles()){
				initFileConfig(child, configs);
			}
		}
	}

	public Configuration getConfig(){
		return Config;
	}
}
